package com.fwx.system.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fwx.common.core.domain.constants.CacheConstants;
import com.fwx.common.core.domain.constants.JwtConstants;
import com.fwx.common.core.domain.domain.R;
import com.fwx.common.core.domain.enums.ResultCode;
import com.fwx.common.core.domain.enums.UserIdentity;
import com.fwx.common.redis.service.RedisService;
import com.fwx.common.security.service.TokenService;
import com.fwx.system.Service.ISySUserService;
import com.fwx.system.domain.SysUser;
import com.fwx.system.mapper.SysUserMapper;
import com.fwx.system.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;


@Service
/*动态刷新*/
@RefreshScope
public class SysUserServiceImpl implements ISySUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisService redisService;
    @Autowired
    private TokenService tokenService ;

    @Value("${jwt.secret}")
    private String secret;
    @Override
    public R<String> login(String userAccount, String password) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
         //select password from tb_sys_user where user_account = #{userAccount}
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper
                .select(SysUser::getUserId,SysUser::getPassword).eq(SysUser::getUserAccount,userAccount));
        //R loginResult = new R();
//        try{
//            FileInputStream fileInputStream = new FileInputStream("a.txt");
//        } catch (FileNotFoundException e) {
//            throw new RuntimeException(e);
//        }
        if(sysUser == null) {
            /*loginResult.setCode(ResultCode.FAILED_USER_NOT_EXISTS.getCode());
            loginResult.setMsg(ResultCode.FAILED_USER_NOT_EXISTS.getMsg());*/
            return R.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if(BCryptUtils.matchesPassword(password,sysUser.getPassword())) {
           /* loginResult.setCode(ResultCode.SUCCESS.getCode());
            loginResult.setMsg(ResultCode.SUCCESS.getMsg());*/
            //用于身份认证机制
            return R.ok(tokenService.createToken(sysUser.getUserId(), secret,UserIdentity.ADMIN.getValue()));
        }
        //loginResult.setCode(ResultCode.FAILE_LOGIN.getCode());
        //loginResult.setMsg(ResultCode.FAILE_LOGIN.getMsg());
        return R.fail(ResultCode.FAILE_LOGIN);
    }
}
